<template>
  <div>
    <div class="title">
      <span>资金账户</span>
      <div class="title-btn">
        <el-button type="info" @click="getAll()" style="padding-left: 15px">刷新</el-button>
        <el-button type="info" @click="initInsertAndUpdate()" style="padding-left: 15px">新增</el-button>
      </div>
    </div>
    <template>
      <el-table show-summary :data="tableData" style="width: 100%" v-loading="loading" 
        :summary-method="getSummaries"
        :default-sort="{prop: 'date', order: 'descending'}">
        <el-table-column type="index" width="50"  align="center"></el-table-column>
        <el-table-column prop="accountName" label="名称" sortable align="center"></el-table-column>
        <el-table-column  prop="moneyAmount" label="金额" sortable align="center"></el-table-column>
        <el-table-column prop="state" label="是否启用" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              disabled>
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column  prop="createTime" label="创建时间" sortable align="center"></el-table-column>

        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="initInsertAndUpdate(scope.row)">编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="deleteCheck(scope.row.id)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--  弹窗 : 新增/修改  -->
      <el-dialog
        :title="!insertAndUpdateForm.id ? '新增' : '修改'"
        :visible.sync="insertAndUpdateVisible"
        width="40%"
      >
        <el-form ref="insertAndUpdateForm" :rules="rules" :model="insertAndUpdateForm" label-width="40%">
          <el-form-item label="名称："  style="width: 70%" prop="accountName">
            <el-input v-model="insertAndUpdateForm.accountName"></el-input>
          </el-form-item>
          <el-form-item label="金额：" style="width: 70%" prop="moneyAmount">
            <el-input v-model="insertAndUpdateForm.moneyAmount"></el-input>
          </el-form-item>
          <el-form-item label="是否启用：" style="width: 70%">
            <el-switch
              v-model="insertAndUpdateForm.state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0">
            </el-switch>
          </el-form-item>
         
          <el-form-item label="备注：" style="width: 70%" prop="remark">
            <el-input type="textarea" v-model="insertAndUpdateForm.remark"></el-input>
          </el-form-item>
         </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="insertAndUpdateVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateDtoInit()">确 定</el-button>
        </div>
      </el-dialog>

    </template>

  </div>
</template>

<script>
export default {
  created() {
    this.getAll()
  },
  data() {
    const validateMoney = (rule, value, callback) => {//包含小数的数字
        let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
        if (value === '') {
            callback(new Error('请输入金额'));
        } else if (!reg.test(value)) {
            callback(new Error('请输入数字'));
        } else {
            callback();
        }
    };
    return {
      loading: false,
      insertAndUpdateVisible: false,
      rules: {
          accountName: [
            { required: true, message: '请输入名称', trigger: 'blur' }
          ],
          moneyAmount: [
            { required: true, validator: validateMoney, trigger: "blur" }
          ],
      },    
      insertAndUpdateForm: {
        accountName: '',
        moneyAmount: '',
        remark: '',
        state: 1
      },
      tableData: [
        {
          "id": 0,
          "accountName": "",
          "moneyAmount": "0",
          "remark": "",
          "createTime": "2021-05-05 12:12:12",
          "state": 1
        }
      ],
      dto: {
        "id": 0,
        "accountName": "",
        "moneyAmount": "0",
        "remark": "",
        "state": 1
      }
    }
  },
  methods: {
    async getAll() {
      const {data: res} = await this.$http.get("/capitalAccount/getAll")
      if (res.code != 200) {
        return this.$message.error(res.msg)
      }
      console.log(res)
      this.tableData = res.data
  
    },
    updateDtoInit(id) {
      this.$refs['insertAndUpdateForm'].validate(async valid => {
        if (valid) {
          const {data: res} = await this.$http.post("/capitalAccount/saveOne", this.insertAndUpdateForm)
          if (res.code != 200) {
            return this.$message.error(res.msg)
          }
          console.log(res)
          this.$message.success(res.msg)
          this.insertAndUpdateVisible = false
          this.getAll()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 新增或修改弹窗初始化
    async initInsertAndUpdate(row) {
      this.insertAndUpdateVisible = true;
      if(this.$refs['insertAndUpdateForm']) {
        this.resetForm('insertAndUpdateForm')
      }
      if(row) {
        Object.assign(this.insertAndUpdateForm, row)
      }
    },
    getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计';
            return;
          }
          if(column.label == '金额') {
            const values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0);
              sums[index] += ' 元';
            } else {
              sums[index] = '';
            }
          }
        });

        return sums;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.insertAndUpdateForm = {
        accountName: '',
        moneyAmount: '',
        remark: '',
        state: 1
      }
    }
  }
}
</script>

<style scoped>
  
  .title-btn {
    float: right;
    padding-right: 30px;
    margin: 15px 0;
  }
</style>
